package com.atwei.mango.system.securityHandler;

import com.alibaba.druid.util.StringUtils;
import com.atwei.mango.system.account.entity.Account;
import com.atwei.mango.system.account.service.AccountService;
import com.atwei.mango.system.commen.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @Classname UserAuthenticationProvider
 * @Description 身份验证处理器
 * @Date 2022/6/8 15:51
 * @Author liuwei
 */
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    AccountService accountService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            throw new UsernameNotFoundException("用户名或密码不能为空");
        }
        Account account = accountService.loadAccountByName(name);

        if (null == account){
            throw new UsernameNotFoundException("用户名不存在");
        }
        if (!account.getPassword().equals(MD5Util.mD5(password))){
            throw new BadCredentialsException("用户名或密码错误");
        }
        // todo 加载权限信息和用户信息
        SysAccount sysAccount = new SysAccount();
        sysAccount.setId(account.getId());
        sysAccount.setAccountName(account.getAccountName());
//        sysAccount.setPassword(account.getPassword());
        return new UsernamePasswordAuthenticationToken(sysAccount,password,sysAccount.getAuthorities());
    }

    /**
     * 支持指定的身份验证
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
